import React, { ReactElement, useRef, useEffect, useState, RefObject } from 'react'
import { Modal, Form, FormInstance, Input, message, Radio, TreeSelect, Select } from 'antd'
import moment, { Moment } from 'moment'
import { addAccountRequest, updateAccountRequest, getPortEnumRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import { AccountSchema } from '@src/components/schema/account'
import { DepartmentSchema } from '@src/components/schema/departmentSchema'
import Upload, { uploadFile } from '@components/upload'
import { FileSchema } from '@src/components/schema/fileSchema'
import _ from 'lodash'
import { TreeData } from '@src/components/schema/tree'
import Dictionary, { DictionaryItem } from '@js/dictionary'
import { checkIdCard } from '@js/identityTest';

// 验证身份证
function validateLicense (value: string) {
  if (typeof value === 'string' && value.length) {
    const e = checkIdCard.test(value)
    if (e) {
      return Promise.reject(new Error(e))
    }
  }
  return Promise.resolve()
}

const { Item } = Form
const { Option } = Select

const genderOptiosn = [
  { label: '男', value: '男' },
  { label: '女', value: '女' }
]
const statusOptions = [
  { label: '在职', value: 1 },
  { label: '离职', value: 0 }
]

interface Props {
  visible: boolean
  hide: () => void
  data: AccountSchema | null
  department: DepartmentSchema | null
  refreshData: () => void
  treeData: TreeData[]
}

interface FormData {
  id?: string
  structureid?: string
  tenant_code?: string
  realname: string
  mobile: string
  username: string
  email: string
  gender: string
  ico?: FileSchema[]
  paddword?: string
  entry_datetime: Moment
  practice_datetime: Moment
  positional_datetime: Moment
}

async function submitHandle (d: FormData, department: DepartmentSchema | null, refreshData: () => void, hide: () => void): Promise<void> {
  let e: Error | null = null
  const data: { [k: string]: any } = {
    ...d
  }
  const h = message.loading('提交中', 120)
  if (d.ico instanceof Array && d.ico.length > 0) {
    const files = await uploadFile(d.ico)
    data.ico = files.map(li => li.id).join()
  }
  if (d.structureid === undefined && department !== null) {
    data.structureid = department.id
  }
  if (d.tenant_code === undefined && department !== null) {
    data.tenant_code = department.tenant_code
  }
  if (d.id === undefined) {
    const r = await awaitWrap(addAccountRequest(data))
    e = r[0]
  } else {
    const r = await awaitWrap(updateAccountRequest(data))
    e = r[0]
  }
  h()
  if (e === null) {
    message.success(d.id === undefined ? '添加成功' : '更新成功').then(null, null)
    refreshData()
    hide()
  }
}

function initData (data: AccountSchema, formRef: RefObject<FormInstance>): void {
  const o: { [k: string]: any } = { ..._.cloneDeep(data) }
  const keys = Object.keys(o)
  keys.forEach(k => {
    if (o[k] === null) {
      o[k] = undefined
    }
  })
  if (typeof o.ico === 'object' && o.ico !== null) {
    o.ico.name = o.ico.original_filename
    o.ico = [o.ico]
  } else {
    o.ico = []
  }
  if (typeof o.entry_datetime === 'number' && o.entry_datetime !== 0) {
    o.entry_datetime = moment(o.entry_datetime * 1000)
  }
  if (typeof o.practice_datetime === 'number' && o.practice_datetime !== 0) {
    o.practice_datetime = moment(o.practice_datetime * 1000)
  }
  if (typeof o.positional_datetime === 'number' && o.positional_datetime !== 0) {
    o.positional_datetime = moment(o.positional_datetime * 1000)
  }
  formRef.current?.setFieldsValue(o)
}

// 初始化职务列表
async function initPosts (setPorts: (v: string[]) => void): Promise<void> {
  const [e, d] = await awaitWrap(getPortEnumRequest())
  if (e === null && d instanceof Array) {
    setPorts(d)
  }
}

function Main ({ visible, hide, data, department, treeData, refreshData }: Props): ReactElement {
  const ref = useRef<FormInstance>(null)
  const [isEdit, setIsEdit] = useState(false)
  const [posts, setPosts] = useState<string[]>([])
  const [options, setOptions] = useState<DictionaryItem[]>([])
  useEffect(() => {
    const d = new Dictionary()
    d.init('考核类别')
      .then(() => {
        setOptions(d.getList('考核类别'))
      })
      .catch(e => console.error(e))
  }, [])
  useEffect(() => {
    if (visible) {
      if (data === null) {
        setIsEdit(false)
        ref.current?.resetFields()
      } else {
        setIsEdit(true)
        initData(data, ref)
      }
    } else {
      ref.current?.resetFields()
    }
  }, [visible])
  useEffect(() => {
    initPosts(setPosts).catch(e => console.error(e))
  }, [])
  return (
    <Modal title={data !== null ? '编辑账号' : '新增账号'} visible={visible} onOk={() => ref.current?.submit()} maskClosable={false} onCancel={() => hide()}>
      <Form ref={ref} labelCol={{ flex: '68px' }} initialValues={{ gender: '男' }} onFinish={async d => await submitHandle(d, department, refreshData, hide)}>
        <Item name='id' noStyle><span /></Item>
        <Item name='accountid' noStyle><span /></Item>
        <Item name='tenant_code' noStyle><span /></Item>
        <Item label='部门' name='structureid' rules={[{ required: true, message: '部门不能为空' }]}>
          <TreeSelect
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={treeData}
            placeholder="请选择"
            treeDefaultExpandAll
          />
        </Item>
        <Item label='姓名' name='realname' rules={[{ required: true, message: '姓名不能为空' }]}>
          <Input placeholder='请输入' />
        </Item>
        <Item label='职务' name='post'>
          <Select placeholder='请选择'>
            {posts.map((li, i) => <Option key={i} value={li}>{li}</Option>)}
          </Select>
        </Item>
        <Item name='license' label='身份证' rules={[{ required: true, message: '身份证不能为空' }, { validator: (rule: any, value: string) => validateLicense(value) }]}>
          <Input placeholder='请输入' maxLength={18} />
        </Item>
        <Item label='手机号' name='mobile' rules={[{ required: true, message: '手机号不能为空' }]}>
          <Input placeholder='请输入' maxLength={11} />
        </Item>
        <Item label='账号' name='username' rules={[{ required: true, message: '账号不能为空' }]}>
          <Input placeholder='请输入' />
        </Item>
        <Item label='邮箱' name='email'>
          <Input placeholder='请输入' />
        </Item>
        <Item label='性别' name='gender'>
          <Radio.Group options={genderOptiosn} />
        </Item>
        <Item label='考核方式' name='employee_type'>
          <Select placeholder='请选择'>
            {options.map((li, i) => {
              return <Option key={i} value={li.value}>{li.title}</Option>
            })}
          </Select>
        </Item>
        {isEdit
          ? (
            <Item label='是否在职' name='status'>
              <Radio.Group options={statusOptions} />
            </Item>
            )
          : null}
        <Item label='头像' name='ico'>
          <Upload accept='.png,.jpg,.jpeg' maxLength={1} image />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
